<template>
  <div>
    <h2>Ajax 请求 json-server 接口</h2>
    <h2>test == {{ test }}</h2>
    <button @click="getlist">点击获取list</button>
    <div>
      <h2 v-for="(l, i) in list" :key="i">
        {{ l.username }} -- {{ l.id }}
        <span @click="deleteOne(l, i)">删除</span> ----
        <span @click="updateOne(l, i)">修改</span>
      </h2>
    </div>
    <div>
      <h2>添加用户 - 注册</h2>
      <p>
        <input type="text" placeholder="请输入用户名" v-model="form.username" />
      </p>
      <p>
        <input type="text" placeholder="请输入手机号" v-model="form.phone" />
      </p>
      <p>
        <input type="text" placeholder="请输入邮箱" v-model="form.email" />
      </p>
      <p>
        <input type="text" placeholder="请输入密码" v-model="form.password" />
      </p>
      <button @click="submitData">点击提交</button>
      <button @click="resetData">重置数据</button>
    </div>
  </div>
</template>

<script>
// 增删改查
export default {
  name: "ajax",
  data() {
    return {
      test: "2110 - so great",
      list: [],
      form: {},
    };
  },
  methods: {
    updateOne() {
      var value = window.prompt(i, l.username);
      if (value) {
        $.ajax({
          url: "http://localhost:2110/list/" + l.id,
          type: "patch",
          data: {
            username: value,
          },
          success: (res) => {},
        });
      }
    },
    deleteOne(l, i) {
      $.ajax({
        url: "http://localhost:2110/list/" + l.id,
        type: "delete", // 删除 数据
        success: (res) => {
          //   this.list.splice(i, 1);
          this.getlist();
        },
      });
    },
    submitData() {
      // 提交用post 提交
      //   $.ajax({
      //     url: "http://localhost:2110/list",
      //     type: "POST",
      //     data: this.form,
      //     success: (res) => {
      //       console.log(res);
      //       this.form = {};
      //       this.getlist();
      //     },
      //   });

      $.post("http://localhost:2110/list", this.form).then((res) => {
        this.form = {};
        this.getlist();
      });
    },
    resetData() {
      this.form = {};
    },
    getlist() {
      $.get("http://localhost:2110/list").then((res) => {
        console.log(res);
        this.list = res;
      });
    },
  },
  created() {
    this.getlist();
  },
  mounted() {
    $.ajax({
      url: "http://localhost:2110/test",
      type: "get",
      dataType: "json",
      success: (res) => {
        console.log(res);
        this.test = res[0];
      },
    });
  },
};
</script>